;(function($){    
    $.fn.rotate = function(type){             
        var rotate = document.body.filters ? ieRotate : canvasRotate;        
        return this.each(function(k, v){
            var r = getRotate(v);
            type > 0 ? ++r : --r;            
            if(r > 3){
                r = 0;
            }
            if(r < 0){
                r = 3;
            }
            rotate(v, r);
        });        
    }
    function getRotate(img){
        return Number($(img).attr("data-rotate")) || 0;			
    }       
    //ie 滤镜旋转
    function ieRotate(img, r){
        var parent = img.parentNode;
        img.style.position = "absolute"
        img.style.top = "-1000px"; 
        parent.style.position ="relative";
        switch (r) {
        case 1:
        case 3:
            parent.style.height = img.width;
            parent.style.width = img.height;
            break;
        case 0:
        case 2:
            parent.style.width = img.width;
            parent.style.height = img.height;
            break;
        }
        img.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ r +')';
        img.style.top = "0px";
        img.setAttribute("data-rotate", r );
    } 
    //canvas旋转
    function canvasRotate(img, r){
        var canvas = $("#canvas_" + img.id)[0];
        if(!canvas){
            canvas = document.createElement("canvas");
        }        
        context = canvas.getContext("2d"),
        x = 0, y = 0;
        canvas.id = "canvas_" + img.id;
        img.style.position = "absolute";
        img.style.visibility = "hidden";

        switch (r) {
        case 0:
            canvas.width = img.width;
            canvas.height = img.height;
            x =0; y = 0;
        break;
        case 1:
            canvas.width = img.height;
            canvas.height = img.width;	
            x = 0; y = -img.height;
        break;							
        case 2:
            canvas.width = img.width;
            canvas.height = img.height;
            x = -img.width; y = -img.height;
        break;							
        case 3:
            canvas.width = img.height;
            canvas.height = img.width;
            x = -img.width; y = 0;
        break;
        }
        context.clearRect(0, 0, img.width, img.height);
        context.save();
        context.rotate(r * 90 * Math.PI / 180);
        context.drawImage(img, x, y, img.width, img.height);
        context.restore();
        img.parentNode.appendChild(canvas);
        img.setAttribute("data-rotate", r );
    }
})(jQuery);